<?php

class Model_Listing_Attribute extends Ac_Model
{

   const TYPE = 5;
   //protected static  $_collection = 'listing_attribute';
   protected static  $_collection = 'attributs';

    /**
     *
     * @var array define the requirements for this model
     */
    protected static $_requirements = array(
     //   'em'  => array('Required', 'Validator:EmailAddress'), //Email
        'tg'  => array('Array'), //Tags
        'path'  => array('Array'), //Path
    );

    protected static $_transcript = array(
        '_id'  => '_id',
        'nm_en' => 'name_en',
        'nm_tc' => 'name_tc',
        'nm_sc' => 'name_sc',
        'type' => 'type',
        'path' => 'path',
        'or'   => 'order',
        'tg'   => 'tags'
    );

    public function __construct($data = array(), $config = array())
	{
        //$config['collection'] = 'listing_attribute';
        $config['collection'] = 'attributs';
        self::ensureIndex(array('path'));
        self::ensureIndex(array('type'));
        self::ensureIndex(array('nm_en'));
        self::ensureIndex(array('nm_tc'));
        self::ensureIndex(array('or'));
        self::ensureIndex(array('tg'));
        parent::__construct($data, $config);
    }

    public function __get($name)
    {
        if($name == 'name') {
            return parent::__get('nm_sc');
        } else {
            return parent::__get($name);
        }
    }
    
    public function __isset($name) {
        $val = self::__get($name);
        return!empty($val) ? true : parent::__isset($name);
    }

    public function getLevel()
    {
        return count($this->path);
    }

    public function getParent()
    {
        return self::find($this->path[count($this->path) - 2]);
    }

    public function getParentTree()
    {
        $res = array();
        foreach($this->path as $cat) {
            $res[] = self::find($cat);
        }
        return $res;
    }

    public function getChildren($all = false)
    {
        if ($all) {
            $critearia = array('path' => $this->_id);
        } else {
            $critearia = array('path.'.($this->getLevel()-1) => $this->_id, 'path' => array('$size' => ($this->getLevel()+1)));
        }

        return self::all($critearia);
    }

    public static function getTypes()
    {
        $connection = Shanty_Mongo::getWriteConnection(Model_Listing_Attribute::$_connectionGroup);
        $db  = $connection->selectDB(Model_Listing_Attribute::$_db);
        $type = $db->command(array("distinct" => Model_Listing_Attribute::$_collection, "key" => "type"));
        return $type['values'];
    }
}
